#!/bin/bash
set -euo pipefail

DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
ROOT_DIR="$( cd "$DIR"/../.. && pwd )"
BUILD_DIR="$ROOT_DIR"/build

. "$ROOT_DIR/config.sh"

function usage {
	echo "Current '$channel' version: `$DIR/get_current_version $channel`" >&2
	echo >&2
	cat >&2 <<DONE
Usage: $0 [-c CHANNEL] -v VERSION

For non-release versions, specify numeric version only (e.g., 5.0.30).
DONE
	exit 1
}

channel="release"
version=""
while getopts "c:v:" opt; do
	case $opt in
		c)
			channel="$OPTARG"
			;;
		v)
			version="$OPTARG"
			;;
		*)
			usage
			;;
	esac
	shift $((OPTIND-1)); OPTIND=1
done

if [ -z "$version" ]; then
	usage
fi

current_version=`$DIR/get_current_version $channel`
if [ $current_version = 'null' ]; then
	current_version="0.0.1"
fi

if [ $channel != "release" ]; then
	rev=$($DIR/get_last_rev $channel $version)
	((++rev))
	main_version=$version
	version="$version$channel$rev"
fi

# Use beta Google Docs endpoint
if [ $channel = "beta" ]; then
        export ZOTERO_GOOGLE_DOCS_API_URL=$ZOTERO_GOOGLE_DOCS_API_URL_BETA
        export ZOTERO_GOOGLE_DOCS_OAUTH_CLIENT_KEY=$ZOTERO_GOOGLE_DOCS_OAUTH_CLIENT_KEY_BETA
fi

# Replace 'beta' with 'beta.' so that semver sorts beta10 > beta9
# https://github.com/npm/node-semver/issues/30#issuecomment-64028037
CMP=$(node -e "console.log(require('semver').compare('$version'.replace('beta', 'beta.'), '$current_version'.replace('beta', 'beta.'), true))")
if [ "$CMP" = "-1" ]; then
	echo "$version must be greater than $current_version"
	exit 1
fi
if [ "$CMP" = "0" ]; then
	echo "$version is the current version"
	exit 1
fi
if [ "$CMP" != "1" ]; then
	echo "Unexpected response $CMP from semver.compare()"
	exit 1
fi

cd "$ROOT_DIR"

echo -n "Building $version"
sleep 1
echo -n .
sleep 1
echo -n .
sleep 1
echo .
sleep 1

./build.sh -p b -v "$version"

if [ $channel != "release" ]; then
	# Add Git commit hash to XPI files
	hash=$(git rev-parse --short HEAD)
	echo "$version+$hash" > $BUILD_DIR/firefox/build_id
fi

FIREFOX_UPDATE_URL=${FIREFOX_UPDATE_URL/CHANNEL/$channel}
cat "$BUILD_DIR/firefox/manifest.json" | jq ".applications.gecko.update_url = \"$FIREFOX_UPDATE_URL\"" > $BUILD_DIR/firefox/manifest.json-new
mv $BUILD_DIR/firefox/manifest.json-new $BUILD_DIR/firefox/manifest.json

echo
echo manifest.json:
echo
grep '"version"' $BUILD_DIR/firefox/manifest.json
grep update_url $BUILD_DIR/firefox/manifest.json
echo
sleep 2

cd "$DIR"
./sign_xpi
echo "Pushing XPI"

./push_xpi $channel
if [ $channel != "release" ]; then
	./set_last_rev $channel $main_version $rev
fi
